﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the Microsoft Public License (Ms-PL).
// See accompanying file License.txt or copy at http://mews.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Mews.Application
{
    using System;
    using System.Drawing;
    using System.Globalization;
    using System.Reflection;
    using System.Windows.Forms;

    using Mews.Application.Properties;

    /// <summary>Displays information about the application.</summary>
    internal sealed partial class AboutForm : DoneCancelForm
    {
        private static readonly Assembly thisAssembly = typeof(AboutForm).Assembly;

        internal AboutForm(Form owner) : base(owner, Resources.About, false, false, true)
        {
            this.InitializeComponent();

            var largeIcons = new IntPtr[1];
            var smallIcons = new IntPtr[1];
            var iconHandle = NativeMethods.ExtractIconEx(
                thisAssembly.ManifestModule.FullyQualifiedName, 0, largeIcons, smallIcons, 1);
            Icon icon;

            try
            {
                icon = Icon.FromHandle(iconHandle);
            }
            finally
            {
                DestroyAllIcons(largeIcons);
                DestroyAllIcons(smallIcons);
            }

            using (icon)
            {
                this.iconPictureBox.Image = IconHelper.ConvertToBitmap(icon, this.BackColor);
            }

            this.applicationNameLabel.Text = GetAssemblyAttribute<AssemblyProductAttribute>().Product;
            this.versionLabel.Text = string.Format(
                CultureInfo.InvariantCulture, this.versionLabel.Text, thisAssembly.GetName().Version);
            this.copyrightLabel.Text = GetAssemblyAttribute<AssemblyCopyrightAttribute>().Copyright;
        }

        private static T GetAssemblyAttribute<T>()
        {
            return (T)thisAssembly.GetCustomAttributes(typeof(T), false)[0];
        }

        private static void DestroyAllIcons(IntPtr[] icons)
        {
            foreach (var icon in icons)
            {
                if (icon != IntPtr.Zero)
                {
                    NativeMethods.DestroyIcon(icon);
                }
            }
        }
    }
}
